package system_service

import (
	"github.com/APP/global"
	"github.com/APP/internal/models/logs"
	"github.com/gin-gonic/gin"
	"go.uber.org/zap"
	"net"
	"strings"
)

type LogService struct{}

// LogLoginAttempt 记录登录尝试
func (s *LogService) LogLoginAttempt(c *gin.Context, username string, status int, reason string) {
	log := logs.SysLogLogin{
		Username:    username,
		Status:      status,
		Reason:      reason,
		IP:          s.getClientIP(c),
		Platform:    s.getPlatform(c),
		DeviceID:    s.getDeviceID(c),
		AppVersion:  "",
		UserAgent:   c.GetHeader("User-Agent"),
		Country:     "1.0.0",
		Region:      "",
		LoginMethod: "",
		RequestData: nil,
	}
	err := global.APP_DB.Table("sys_log_login").Create(&log).Error
	if err != nil {
		global.APP_LOG.Error("记录登录尝试失败", zap.Error(err))
	}
}

// getClientIP 获取客户端真实IP
func (s *LogService) getClientIP(c *gin.Context) string {
	// 尝试从各种头部获取真实IP
	clientIP := c.GetHeader("X-Forwarded-For")
	if clientIP != "" {
		// X-Forwarded-For 可能包含多个IP，取第一个
		ips := strings.Split(clientIP, ",")
		if len(ips) > 0 {
			return strings.TrimSpace(ips[0])
		}
	}

	clientIP = c.GetHeader("X-Real-IP")
	if clientIP != "" {
		return clientIP
	}

	clientIP = c.GetHeader("X-Forwarded")
	if clientIP != "" {
		return clientIP
	}

	clientIP = c.GetHeader("X-Cluster-Client-IP")
	if clientIP != "" {
		return clientIP
	}

	// 如果都没有，使用RemoteAddr
	ip, _, err := net.SplitHostPort(c.Request.RemoteAddr)
	if err != nil {
		return c.Request.RemoteAddr
	}
	return ip
}

// getPlatform 根据User-Agent判断平台
func (s *LogService) getPlatform(c *gin.Context) string {
	userAgent := strings.ToLower(c.GetHeader("User-Agent"))

	if strings.Contains(userAgent, "windows") {
		return "Windows"
	} else if strings.Contains(userAgent, "macintosh") || strings.Contains(userAgent, "mac os") {
		return "Mac"
	} else if strings.Contains(userAgent, "linux") {
		return "Linux"
	} else if strings.Contains(userAgent, "android") {
		return "Android"
	} else if strings.Contains(userAgent, "iphone") || strings.Contains(userAgent, "ipad") {
		return "iOS"
	}

	return "Unknown"
}

// getDeviceID 生成设备ID（简单实现，实际项目中可能需要更复杂的逻辑）
func (s *LogService) getDeviceID(c *gin.Context) string {
	// 这里简单使用IP+User-Agent的组合作为设备标识
	// 实际项目中可能需要使用更复杂的设备指纹技术
	ip := s.getClientIP(c)
	userAgent := c.GetHeader("User-Agent")

	// 简单的哈希处理
	deviceInfo := ip + "|" + userAgent
	if len(deviceInfo) > 100 {
		deviceInfo = deviceInfo[:100]
	}

	return deviceInfo
}
